package com.atguigu;

import io.minio.*;
import io.minio.errors.MinioException;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * MinIO
 *
 * @author Taeyang
 * @date 2025/3/15
 */
public class Main {
    public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeyException {

        try {
            // 构造MinIO Client
            MinioClient minioClient = MinioClient.builder()
                    .endpoint("http://192.168.100.102:9000")
                    .credentials("minioadmin", "minioadmin")
                    .build();

            // 判断hello-minio桶是否存在
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket("hello-minio").build());
            // 如果不存在
            if (!found) {
                // 创建hello-minio桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket("hello-minio").build());
                // 设置hello-minio桶的访问权限
                String policy = """
                        {
                          "Statement" : [ {
                            "Action" : "s3:GetObject",
                            "Effect" : "Allow",
                            "Principal" : "*",
                            "Resource" : "arn:aws:s3:::hello-minio/*"
                          } ],
                          "Version" : "2012-10-17"
                        }""";
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket("hello-minio").config(policy).build());
            } else {
                // 存在
                System.out.println("Bucket 'hello-minio' already exists.");
            }

            // 上传图片
            minioClient.uploadObject(
                    UploadObjectArgs.builder()
                            .bucket("hello-minio")
                            .object("权志龙.jpg")
                            .filename("C:\\Users\\60301\\Desktop\\GD.jpg")
                            .build());
            System.out.println("上传成功");
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
        }
    }
}